/**
 * 全球指数数据钩子
 */

import { useQuery } from '@tanstack/react-query';
import { get } from '@shared/utils/apiClient';
import { ApiResponse, GlobalIndexesResponse } from '@shared/types/market';
import { getChinaMarketStatus } from '@shared/utils/marketStatus';

// 使用相对路径，Vite会自动代理到后端
const API_BASE = import.meta.env.VITE_API_BASE_URL || '';

interface UseGlobalIndexesOptions {
  regions?: ('americas' | 'europe' | 'hongkong' | 'asia')[];
  includeClosed?: boolean;
}

/**
 * 获取全球主要指数数据
 */
export function useGlobalIndexes(options: UseGlobalIndexesOptions = {}) {
  const { regions, includeClosed = true } = options;
  const marketStatus = getChinaMarketStatus();
  
  // 根据市场状态调整刷新间隔
  const getGlobalIndexRefreshInterval = () => {
    switch (marketStatus) {
      case 'trading':
        return 30000; // 交易时段：30秒
      case 'pre_market':
        return 60000; // 盘前：60秒
      case 'after_hours':
        return 180000; // 盘后：3分钟
      case 'closed':
        return 300000; // 休市：5分钟（全球市场可能仍在交易）
      default:
        return 300000;
    }
  };

  const refreshInterval = getGlobalIndexRefreshInterval();

  return useQuery({
    queryKey: ['globalIndexes', regions, includeClosed],
    queryFn: async () => {
      const params = new URLSearchParams();
      
      if (regions && regions.length > 0) {
        params.append('regions', regions.join(','));
      }
      
      params.append('include_closed', includeClosed.toString());

      const url = `${API_BASE}/api/v1/market/global-indexes?${params.toString()}`;
      
      const response = await get<ApiResponse<GlobalIndexesResponse>>(url);
      
      return response.data;
    },
    refetchInterval: refreshInterval, // 动态刷新间隔
    staleTime: refreshInterval * 0.8, // 设置为刷新间隔的80%
    gcTime: 600000, // 缓存10分钟
    refetchOnWindowFocus: false,
  });
}

